//
//  VipViewModel.swift
//  Qianli
//
//  Created by qianli on 2024/12/2.
//

import Foundation
import Moya

class VipViewModel : ObservableObject{
    static let shared = VipViewModel()
//    @Published var goodsList : [GoodsModel] = []
//    @Published 是 SwiftUI 框架中的一个属性包装器（Property Wrapper），用于创建可观察的属性
    var goodsList : [GoodsModel] = []
    var orderData : OrdersData?
    private var ASpcC7xzzbTIzEXQ:[String:Any]?
    var channelList:[[String:Any]]?
    var waitingOrder:[String:Any]?
    
    var completionHandler: ((_ result:String) -> Void)?
    
    //MARK: - 1.获取可用商品列表
    func ZCYappMADpwrfWpt(goodsRequest: GoodsRequest,completion: @escaping (Result<BaseData, Error>) -> Void){
        NetWorkManager.shared.provider.request(.apiGetGoodsList(goodsRequest: goodsRequest)){ [weak self] result in
            switch result {
            case .success(let response):
                do {
                    let decoder = JSONDecoder()
                    let goodsResults = try decoder.decode(GoodsResult.self, from: response.data)
                    if goodsResults.code == 0{
                        if let data = goodsResults.data{
                            self?.goodsList = data
                        }
                        completion(.success(BaseData(code: 0, msg: "")))
                    }else{
                        completion(.success(BaseData(code: goodsResults.code, msg: goodsResults.msg)))
                        ZacollectModel.shared.vnveDBhaItvpywSl("getGoodsList","\(goodsResults.code)-\(goodsResults.msg)")
                    }
                } catch {
                    completion(.failure(error))
                    ZacollectModel.shared.vnveDBhaItvpywSl("getGoodsList","处理出错:\(error.localizedDescription)")
                }
            case .failure(let error):
                self?.completionHandler?("failure：\(error.localizedDescription)")
                ZacollectModel.shared.vnveDBhaItvpywSl("getGoodsList","请求出错:\(error.localizedDescription)")
            }
        }
    }
    
   //MARK: - 2.获取订单列表
    func ouraS2LUid0tda1u(pagination:Pagination){
        NetWorkManager.shared.provider.request(.apiGetOrderList(orderlistRequest: PaginationRequest(pagination: pagination))){ [weak self] result in
            switch result {
            case .success(let response):
                do {
                    let decoder = JSONDecoder()
//                    decoder.dateDecodingStrategy = .iso8601 //一律用String,如果用Date需要进行iso8601转换，而接口中的iso8601格式居然是不一致的！！！
                    let orderResults = try decoder.decode(OrdersResult.self, from: response.data)
                    //{"code":0,"msg":"获取订单列表成功","data":{"total":0,"data":[],"stats":null}} //接口成功，但没有订单数据的情况
                    self?.orderData = orderResults.data
                    self?.completionHandler?("")
                } catch {
//                    print("getOrderList json error : \(error)")
                    self?.completionHandler?("error：\(error.localizedDescription)")
                    ZacollectModel.shared.vnveDBhaItvpywSl("getMyOrderList","处理出错:\(error.localizedDescription)")
                }
            case .failure(let error):
                print("getOrderList failure error : \(error)")
                self?.completionHandler?("failure：\(error.localizedDescription)")
                ZacollectModel.shared.vnveDBhaItvpywSl("getMyOrderList","请求出错:\(error.localizedDescription)")
            }
        }
    }
    
    func Me8MVHEVF8tiNcjw(_ good_Id: Int, completion: @escaping (Result<BaseData, Error>) -> Void) {
        NetWorkManager.shared.provider.request(.apiGetOrderInfo(goodId: good_Id)) {[weak self] result in
            switch result {
            case .success(let response):
                do {
                    // 解析 JSON 为字典
                    if let json = try JSONSerialization.jsonObject(with: response.data, options: []) as? [String: Any]{
                        if json["code"] as? Int == 0{
                            if let dataDict = json["data"] as? [String: Any] {
                                if let self = self{
                                    self.ASpcC7xzzbTIzEXQ = dataDict
                                }
                                completion(.success(BaseData(code: 0, msg: "")))
                            } else {
                                completion(.success(BaseData(code: -1, msg: "getOrderInfo:Invalid")))
                            }
                        }else{
                            if let iCode = json["code"] as? Int,let msg = json["msg"] as? String{
                                completion(.success(BaseData(code: iCode, msg: msg)))
                            }else{
                                completion(.success(BaseData(code: -2, msg: "getOrderInfo:Failed")))
                            }
                        }
                    }
                } catch {
                    completion(.failure(error))
                }
            case .failure(let error):
                completion(.failure(error))
            }
        }
    }
    
    func XiambxbVszW7LFim(completion: @escaping (Result<BaseData, Error>) -> Void){
        NetWorkManager.shared.provider.request(.apiGetEnablePayList) {[weak self]result in
            switch result {
            case .success(let response):
                do {
                    if let json = try JSONSerialization.jsonObject(with: response.data, options: []) as? [String: Any]{
                        if json["code"] as? Int == 0{
                            if let dataArray = json["data"] as? [[String: Any]],dataArray.count>0 {
                                self?.channelList = dataArray
                                completion(.success(BaseData(code: 0, msg: "")))
                            }else {
                                self?.channelList = nil
                                completion(.success(BaseData(code: -3, msg: "channelList:invalid")))
                            }
                        }else{
                            if let iCode = json["code"] as? Int,let msg = json["msg"] as? String{
                                completion(.success(BaseData(code: iCode, msg: msg)))
                            }else{
                                completion(.success(BaseData(code: -2, msg: "channelList:failed")))
                            }
                        }
                    }
                } catch {
                    completion(.failure(error))
                }
            case .failure(let error):
                completion(.failure(error))
            }
        }
    }
    
    func QLq8RYY7nk51xXYT(completion: @escaping (Result<BaseData, Error>) -> Void){
        if let orderDict = self.ASpcC7xzzbTIzEXQ{
            NetWorkManager.shared.provider.request(.apiPreCreateOrder(dataDict: orderDict)) {[weak self] result in
                switch result {
                case .success(let response):
                    do {
                        if let json = try JSONSerialization.jsonObject(with: response.data, options: []) as? [String: Any]{
                            if json["code"] as? Int == 0{
                                if let dataDict = json["data"] as? [String: Any] {
                                    if let self = self{
                                        self.ASpcC7xzzbTIzEXQ = dataDict
                                    }
                                    completion(.success(BaseData(code: 0, msg: "")))
                                } else {
                                    completion(.success(BaseData(code: -1, msg: "preCreateOrder:invalid")))
                                }
                            }else{
                                if let iCode = json["code"] as? Int,let msg = json["msg"] as? String{
                                    completion(.success(BaseData(code: iCode, msg: msg)))
                                }else{
                                    completion(.success(BaseData(code: -2, msg: "preCreateOrder:failed")))
                                }
                            }
                        }
                    } catch {
                        completion(.failure(error))
                    }
                case .failure(let error):
                    completion(.failure(error))
                }
            }
        }
    }
    
    func k4Yncbet8g58oOuU(completion: @escaping (Result<BaseData, Error>) -> Void){
        if let orderDict = self.ASpcC7xzzbTIzEXQ{
            NetWorkManager.shared.provider.request(.apiGetOrderInfoWaitPay(dataDict: orderDict)) {[weak self] result in
                switch result {
                case .success(let response):
                    do {
                        if let json = try JSONSerialization.jsonObject(with: response.data, options: []) as? [String: Any]{
                            if json["code"] as? Int == 0{
                                if let dataDict = json["data"] as? [String: Any] {
                                    if dataDict["trade_status"] as? String == "WAIT_BUYER_PAY"{ //="TRADE_SUCCESS"表示完成,"TRADE_CLOSED"表示关闭
                                        if let self=self{
                                            self.ASpcC7xzzbTIzEXQ = dataDict
                                        }
                                        completion(.success(BaseData(code: 0, msg: "")))
                                    }
                                    else {
                                        completion(.success(BaseData(code: -3, msg: "getOrderInfoWaitPay:errState")))
                                    }
                                } else {
                                    completion(.success(BaseData(code: -1, msg: "getOrderInfoWaitPay:Invalid")))
                                }
                            }else{
                                if let iCode = json["code"] as? Int,let msg = json["msg"] as? String{
                                    completion(.success(BaseData(code: iCode, msg: msg)))
                                }else{
                                    completion(.success(BaseData(code: -2, msg: "getOrderInfoWaitPay:failed")))
                                }
                            }
                        }
                    } catch {
                        completion(.failure(error))
                    }
                case .failure(let error):
                    completion(.failure(error))
                }
            }
        }
    }
    
    
    func u6395Tvrtx05KWv4(_ channelId:Int, completion: @escaping (Result<BaseData, Error>) -> Void){
//已弃用
        guard var orderDict = self.ASpcC7xzzbTIzEXQ else {
            completion(.success(BaseData(code: -1, msg: "purchaseOrder:notExist")))
            return
        }
        
        orderDict["pay_id"] = channelId
        NetWorkManager.shared.provider.request(.apiPurchaseOrder(dataDict: orderDict)) {[weak self] result in
            switch result {
            case .success(let response):
                do {
                    if let json = try JSONSerialization.jsonObject(with: response.data, options: []) as? [String: Any]{
                        if json["code"] as? Int == 0{
                            if let dataDict = json["data"] as? [String: Any] {
                                self?.waitingOrder = dataDict
                                if let payInfo = dataDict["pay_info"] as? [String:Any]{
                                    if let adapay = payInfo["ailipay_info"] as? [String:Any]{
                                        if let url = adapay["qr_code"] as? String,url.hasPrefix("http"){
                                            completion(.success(BaseData(code: 0, msg: url)))
                                            return
                                        }
                                    }
                                 
                                    if let adapay = payInfo["adapay_info"] as? [String:Any]{
                                        if let url = adapay["pay_url"] as? String,url.hasPrefix("http"){
                                            completion(.success(BaseData(code: 0, msg: url)))
                                            return
                                        }
                                    }
                                     
                                }
                            }
                            completion(.success(BaseData(code: -1, msg: "purchaseOrder:Invalid")))
                        }else{
                            if let iCode = json["code"] as? Int,let msg = json["msg"] as? String{
                                completion(.success(BaseData(code: iCode, msg: msg)))
                            }else{
                                completion(.success(BaseData(code: -2, msg: "purchaseOrder:failed")))
                            }
                        }
                    }
                } catch {
                    completion(.failure(error))
                }
            case .failure(let error):
                completion(.failure(error))
            }
        }
    }
    
    func J85uYzv7U9QtRAtT(completion: @escaping (Result<BaseData, Error>) -> Void){
        guard let orderDict = self.waitingOrder else {
            completion(.success(BaseData(code: -1, msg: "getOrderData:notExist")))
            ZacollectModel.shared.vnveDBhaItvpywSl("getOrderData","不存在waitingOrder")
            return
        }
        
        NetWorkManager.shared.provider.request(.apiGetOrderData(dataDict: orderDict)) {result in
            switch result {
            case .success(let response):
                do {
                    if let json = try JSONSerialization.jsonObject(with: response.data, options: []) as? [String: Any]{
                        if json["code"] as? Int == 0{
                            if let dataDict = json["data"] as? [String: Any] {
                                if let status = dataDict["trade_status"] as? String{
                                    //"WAIT_BUYER_PAY"待支付 "TRADE_SUCCESS"表示完成,"TRADE_CLOSED"表示关闭
                                    completion(.success(BaseData(code: 0, msg: status)))
                                    return
                                }
                            }
                            completion(.success(BaseData(code: -1, msg: "getOrderData:invalid")))
                            ZacollectModel.shared.vnveDBhaItvpywSl("getOrderData","无效data")
                        }else{
                            if let iCode = json["code"] as? Int,let msg = json["msg"] as? String{
                                completion(.success(BaseData(code: iCode, msg: msg)))
                                ZacollectModel.shared.vnveDBhaItvpywSl("getOrderData","\(iCode)-\(msg)")
                            }else{
                                completion(.success(BaseData(code: -2, msg: "getOrderData:Failed")))
                                ZacollectModel.shared.vnveDBhaItvpywSl("getOrderData","未知code或msg")
                            }
                        }
                    }
                } catch {
                    completion(.failure(error))
                    ZacollectModel.shared.vnveDBhaItvpywSl("getOrderData","处理出错:\(error.localizedDescription)")
                }
            case .failure(let error):
                completion(.failure(error))
                ZacollectModel.shared.vnveDBhaItvpywSl("getOrderData","请求出错:\(error.localizedDescription)")
            }
        }
    }
    
    func EhAjgX7RNXBE6Vai(receiptStr:String, completion: @escaping (Result<BaseData, Error>) -> Void){
        NetWorkManager.shared.provider.request(.apiPurchaseApplePay(receiptData: receiptStr)) {result in
            switch result {
            case .success(let response):
                do {
                    if let json = try JSONSerialization.jsonObject(with: response.data, options: []) as? [String: Any]{
                        if json["code"] as? Int == 0{
                            if let dataDict = json["data"] as? [String: Any] {
                                if let status = dataDict["trade_status"] as? String{
                                    //"WAIT_BUYER_PAY"待支付 "TRADE_SUCCESS"表示完成,"TRADE_CLOSED"表示关闭
                                    completion(.success(BaseData(code: 0, msg: status)))
                                    return
                                }
                            }
                            completion(.success(BaseData(code: -1, msg: "purchaseApplePay:invalid")))
                            ZacollectModel.shared.vnveDBhaItvpywSl("purchaseApplePay","无效data")
                        }else{
                            if let iCode = json["code"] as? Int,let msg = json["msg"] as? String{
                                completion(.success(BaseData(code: iCode, msg: msg)))
                                ZacollectModel.shared.vnveDBhaItvpywSl("purchaseApplePay","\(iCode)-\(msg)")
                            }else{
                                completion(.success(BaseData(code: -2, msg: "purchaseApplePay:Failed")))
                                ZacollectModel.shared.vnveDBhaItvpywSl("purchaseApplePay","未知code或msg")
                            }
                        }
                    }
                } catch {
                    completion(.failure(error))
                    ZacollectModel.shared.vnveDBhaItvpywSl("purchaseApplePay","处理出错:\(error.localizedDescription)")
                }
            case .failure(let error):
                completion(.failure(error))
                ZacollectModel.shared.vnveDBhaItvpywSl("purchaseApplePay","请求出错:\(error.localizedDescription)")
            }
        }
    }
    
    
    
}
